package com.jkoss.wine.shop.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.CryptoUtils;
import com.jkoss.common.util.UuidUtil;
import com.jkoss.wine.merchant.entity.MerchantProduct;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.entity.MerchantProductType;
import com.jkoss.wine.merchant.mapper.MerchantProductMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductNormMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductTypeMapper;
import com.jkoss.wine.shop.entity.Distribution;
import com.jkoss.wine.shop.entity.InventoryWarning;
import com.jkoss.wine.shop.entity.Product;
import com.jkoss.wine.shop.entity.ProductInventory;
import com.jkoss.wine.shop.entity.ProductNorm;
import com.jkoss.wine.shop.entity.ProductType;
import com.jkoss.wine.shop.entity.Shop;
import com.jkoss.wine.shop.entity.ShopAccounts;
import com.jkoss.wine.shop.entity.ShopEmployees;
import com.jkoss.wine.shop.entity.ShopSetting;
import com.jkoss.wine.shop.mapper.DistributionMapper;
import com.jkoss.wine.shop.mapper.InventoryWarningMapper;
import com.jkoss.wine.shop.mapper.ProductInventoryMapper;
import com.jkoss.wine.shop.mapper.ProductMapper;
import com.jkoss.wine.shop.mapper.ProductNormMapper;
import com.jkoss.wine.shop.mapper.ProductTypeMapper;
import com.jkoss.wine.shop.mapper.ShopAccountsMapper;
import com.jkoss.wine.shop.mapper.ShopEmployeesMapper;
import com.jkoss.wine.shop.mapper.ShopMapper;
import com.jkoss.wine.shop.mapper.ShopSettingMapper;
import com.jkoss.wine.shop.service.IShopService;
import com.jkoss.wine.shop.vo.ShopVo;
import com.jkoss.wine.system.entity.MessageNotification;
import com.jkoss.wine.system.mapper.MessageNotificationMapper;

/**
 * 服务实现类
 * 
 * @Author zhouhuajin
 * @Version 1.0, 2018-09-28
 * @See
 * @Since com.jkoss.wine.shop.service.impl
 * @Description: TODO
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
	@Autowired
	private ShopEmployeesMapper shopEmployeesMapper;
	@Autowired
	private ShopAccountsMapper shopAccountsMapper;
	@Autowired
	private MerchantProductTypeMapper merchantProductTypeMapper;
	@Autowired
	private ProductTypeMapper productTypeMapper;
	@Autowired
	private MerchantProductMapper merchantProductMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private MerchantProductNormMapper merchantProductNormMapper;
	@Autowired
	private ProductNormMapper productNormMapper;
	@Autowired
	private ProductInventoryMapper productInventoryMapper;
	@Autowired
	private InventoryWarningMapper inventoryWarningMapper;
	@Autowired
	private DistributionMapper distributionMapper;
	@Autowired
	private ShopSettingMapper shopSettingMapper;
	@Autowired
	private ShopMapper shopMapper;
	@Autowired
	private MessageNotificationMapper messageNotificationMapper;

	@Override
	public boolean verifyRechargePassword(String shopId, String pwd) {
		Shop shop = new Shop();
		shop.setShopId(shopId);
		shop.setOperatingPwd(pwd);
		List<Shop> shops = (List<Shop>) shopMapper.selectOne(shop);
		return shops != null;
	}

	@Override
	public boolean updateSelectShop(Shop shop) {
		return shopMapper.updateAllColumnById(shop) == 1;
	}

	@Override
	public boolean updateShop(Shop shop) throws Exception {

		Shop oldShop = baseMapper.selectById(shop.getShopId());
		if (!CommonUtil.isEquals(oldShop.getMaid(), shop.getMaid())) {
			MessageNotification messageNotification = new MessageNotification();
			// 员工id
			messageNotification.setMeid(shop.getMaid());
			// 标题
			messageNotification.setTitle("新客户资源分配提醒");
			// 内容
			messageNotification.setContent("新客户资源分配提醒,未读提醒");
			// 是否已读：0-未读、1-已读
			messageNotification.setIsread(0);
			// 添加时间
			messageNotification.setAddTime(CommonUtil.getDate());
			// 是否删除
			messageNotification.setDel(0);
			// 操作人
			messageNotification.setOperator(shop.getOperator());
			messageNotificationMapper.insert(messageNotification);
		}
		int i = shopMapper.updateAllColumnById(shop);
		if (i != 1) {
			throw new Exception("更新失败");
		}
		Shop shop2 = new Shop();
		BeanUtils.copyProperties(shop, shop2);
		shop2.setShopId(shop.getShopId());
		Wrapper wrapper = Condition.create().eq("shop_id", shop2.getShopId());
		if (!retBool(shopMapper.update(shop2, wrapper))) {
			throw new Exception("更新失败");
		}
		return true;
	}

	@Override
	public void updateShopState(String shopId, Integer state) throws Exception {
		Shop shop = new Shop();
		shop.setShopId(shopId);
		shop.setShopState(state);
		int i = shopMapper.updateAllColumnById(shop);
		if (i != 1) {
			throw new Exception("修改商店状态失败");
		}
	}

	@Override
	public boolean insertShop(Shop entity) throws Exception {
		// region 添加商店
		// Shop shop = new Shop();
		// BeanUtils.copyProperties(entity, shop);
		// 添加时间
		entity.setAddTime(CommonUtil.getDate());

		// 是否删除：0-未删除、1-已删除、2-不能删除
		entity.setDel(0);
		// 店铺状态：0-停用、 1-启用
		entity.setShopState(1);
		// 门店状态：1-新客户、2-门店建设中、3-门店配货中、4-常规客户
		entity.setState(1);

		// 电话号码
		entity.setMobilePhone(entity.getContactNumber());
		Integer maxShopNum = baseMapper.getMaxShopNum();
		if (maxShopNum == null) {
			maxShopNum = 0;
		}
		maxShopNum += 1;
		entity.setShopNum(maxShopNum.toString());
		entity.setShopState(1);
		entity.setOperatingPwd(CryptoUtils.encodeMD5("123456"));
		if (retBool(baseMapper.insert(entity))) {
			// region 添加ShopEmployees
			ShopEmployees shopEmployees = new ShopEmployees();
			shopEmployees.setShopId(entity.getShopId());
			shopEmployees.setEmployeeName(entity.getContacts());
			shopEmployees.setEmployeeSex(1);
			shopEmployees.setEmployeePhone(entity.getMobilePhone());
			shopEmployees.setAddTime(CommonUtil.getDate());
			shopEmployees.setOperator(entity.getOperator());
			if (!retBool(shopEmployeesMapper.insert(shopEmployees))) {
				throw new Exception("门店雇员新增失败");
			}
			// endregion

			// region 添加ShopAccounts
			ShopAccounts shopAccounts = new ShopAccounts();
			shopAccounts.setShopId(entity.getShopId());
			shopAccounts.setEmployeeId(shopEmployees.getEmployeeId());
			shopAccounts.setAccountNum(entity.getMobilePhone());
			shopAccounts.setAccountPwd(CryptoUtils.encodeMD5("123456"));
			shopAccounts.setAddTime(CommonUtil.getDate());
			shopAccounts.setOperator(entity.getOperator());
			shopAccounts.setPowerStr(baseMapper.getShopAllFunction()); // 新开店铺给所有权限
			shopAccounts.setAccountState(1);
			if (!retBool(shopAccountsMapper.insert(shopAccounts))) {
				throw new Exception("门店雇员帐号新增失败");
			}
			// endregion

			// region 商品类型复制
			List<MerchantProductType> merchantProductTypes = merchantProductTypeMapper.selectList(null);
			List<ProductType> productTypes = new ArrayList<>();
			for (MerchantProductType item : merchantProductTypes) {
				ProductType temp = new ProductType();
				BeanUtils.copyProperties(item, temp);
				temp.setProductTypeId(UuidUtil.getUUID());
				temp.setParentId(item.getMerchantProductTypeId());
				temp.setShopId(entity.getShopId());
				productTypes.add(temp);
			}
			if (productTypes.size() > 0) {
				if (!retBool(productTypeMapper.insertBatch(productTypes))) {
					throw new Exception("商品类型复制失败");
				}
			}
			// endregion

			// 商品复制
			List<MerchantProduct> merchantProducts = merchantProductMapper.selectList(null);
			List<Product> products = new ArrayList<>();
			for (MerchantProduct item : merchantProducts) {
				Product temp = new Product();
				BeanUtils.copyProperties(item, temp);
				temp.setProductId(UuidUtil.getUUID());
				temp.setParentId(item.getMerchantProductId());
				temp.setShopId(entity.getShopId());
				temp.setProductTypeId(getProductTypeId(productTypes, item.getMerchantProductTypeId()));
				temp.setFreightPrice(0);
				products.add(temp);
			}
			if (products.size() > 0) {
				if (!retBool(productMapper.insertBatch(products))) {
					throw new Exception("商品复制失败");
				}
			}

			// region 商品规格复制
			List<MerchantProductNorm> merchantProductNorms = merchantProductNormMapper.selectList(null);
			List<ProductNorm> productNorms = new ArrayList<>();
			for (MerchantProductNorm item : merchantProductNorms) {
				ProductNorm temp = new ProductNorm();
				BeanUtils.copyProperties(item, temp);
				temp.setProductNormId(UuidUtil.getUUID());
				temp.setParentId(item.getMerchantProductNormId());
				temp.setProductId(getProductId(products, item.getMerchantProductId()));
				temp.setShopId(entity.getShopId());
				temp.setNormPrice(item.getSuggestedPrice());
				productNorms.add(temp);
			}
			if (productNorms.size() > 0) {
				if (!retBool(productNormMapper.insertBatch(productNorms))) {
					throw new Exception("商品规格复制失败");
				}
			}
			// endregion

			// TODO: 2018/5/22 总店没有库存概念，后期可能会加，业务上也不是直接复制

			// 商品库存复制
			List<ProductInventory> productInventories = new ArrayList<>();
			for (ProductNorm item : productNorms) {
				ProductInventory temp = new ProductInventory();
				temp.setProductInventoryId(UuidUtil.getUUID());
				temp.setProductNormId(item.getProductNormId());
				temp.setProductId(item.getProductId());
				temp.setShopId(item.getShopId());
				temp.setInventory(0);
				temp.setInventoryNum(null);
				temp.setType(0);
				temp.setOperator(null);
				temp.setAddTime(CommonUtil.getDate());
				temp.setRemark("创建商品自动入库");

				productInventories.add(temp);
			}
			if (productInventories.size() > 0) {
				if (!retBool(productInventoryMapper.insertBatch(productInventories))) {
					throw new Exception("创建商品自动入库失败");
				}
			}

			// 商品库存预警复制
			List<InventoryWarning> inventoryWarnings = new ArrayList<>();
			for (ProductNorm item : productNorms) {
				InventoryWarning temp = new InventoryWarning();
				BeanUtils.copyProperties(item, temp);
				temp.setInventoryWarningId(UuidUtil.getUUID());
				temp.setShopId(entity.getShopId());
				temp.setWarningValue(0);
				inventoryWarnings.add(temp);
			}
			if (inventoryWarnings.size() > 0) {
				if (!retBool(inventoryWarningMapper.insertBatch(inventoryWarnings))) {
					throw new Exception("商品库存预警复制失败");
				}
			}
			// region 分销设置
			Distribution distribution = new Distribution();
			distribution.setDistributionId(UuidUtil.getUUID());
			distribution.setUlBackPercent(0);
			distribution.setOlBackPercent(0);
			distribution.setOlDiscount(100);
			distribution.setOperationTime(CommonUtil.getDate());
			distribution.setOperator(entity.getOperator());
			distribution.setShopId(entity.getShopId());
			if (!retBool(distributionMapper.insert(distribution))) {
				throw new Exception("初始化分销设置失败");
			}
			// endregion
			// region 店铺设置
			ShopSetting shopSetting = new ShopSetting();
			shopSetting.setShopSettingId(UuidUtil.getUUID());
			shopSetting.setShopId(entity.getShopId());
			shopSetting.setOperator(entity.getOperator());
			shopSetting.setOnlineSaleType(0);
			shopSetting.setRechargeAllowGive(0);
			shopSetting.setAddTime(CommonUtil.getDate());
			if (!retBool(shopSettingMapper.insert(shopSetting))) {
				throw new Exception("店铺设置失败");
			}
			// endregion
		}
		// throw new Exception("商品类型复制失败");
		// endregion
		return true;
	}

	private String getProductTypeId(List<ProductType> source, String parentId) {
		if (source != null) {
			for (ProductType productType : source) {
				if (productType.getParentId().equals(parentId)) {
					return productType.getProductTypeId();
				}
			}
		}
		return null;
	}

	private String getProductId(List<Product> source, String parentId) {
		if (source != null) {
			for (Product product : source) {
				if (product.getParentId().equals(parentId)) {
					return product.getProductId();
				}
			}
		}
		return null;
	}

	@Override
	public Page selectVoByPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByPage(page, wrapper));
		return page;
	}

	@Override
	public Page selectVoByshopListPage(Page page, Wrapper wrapper, String fwtm) {
		// TODO Auto-generated method stub
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByshopListPage(page, wrapper, "fwtm"));
		return page;
	}

	@Override
	public Page selectVoByShopOrderListPage(Page page, Wrapper wrapper) {
		// TODO Auto-generated method stub
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByShopOrderListPage(page, wrapper));
		return page;
	}

	@Override
	public ShopVo selectVoById(String id) {
		return baseMapper.selectVoById(id);
	}

}
